package com.soujiayi.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;

import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.Constants;
import com.soujiayi.util.UserKeeper;
import com.soujiayi.weibo.User;

public class SoujiayiLoginActivity extends Activity {

	private EditText name;
	private EditText password;
	private ScrollView scrollView;
	private Button clearNameBtn;
	private Button clearPasswordBtn;
	public static String couponID = null;
	private boolean isNotFromSetting = false;

	private DatabaseManager databaseManager = new DatabaseManager(
			SoujiayiLoginActivity.this);

	private HttpRequester httpRequester;
	private Handler handler;
	private ProgressDialog progressDialog;
	private HttpRequester getMemberInfohttpRequester;
	private Handler getMemberInfohandler;
	private int count_to_uc = 0;
	private int uid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.soujiayilogin);

		isNotFromSetting = this.getIntent().getBooleanExtra(
				Constants.IS_NOT_FROM_SETTING, false);

		clearNameBtn = (Button) findViewById(R.id.login_clear_name);
		clearPasswordBtn = (Button) findViewById(R.id.login_clear_password);

		name = (EditText) findViewById(R.id.login_name);
		name.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				clearNameBtn.setVisibility(s.toString().equals("") ? View.GONE
						: View.VISIBLE);
			}
		});

		password = (EditText) findViewById(R.id.login_password);
		password.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				clearPasswordBtn
						.setVisibility(s.toString().equals("") ? View.GONE
								: View.VISIBLE);
			}
		});

		scrollView = (ScrollView) findViewById(R.id.login_scrollview);
		scrollView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(name.getWindowToken(), 0);
				imm.hideSoftInputFromWindow(password.getWindowToken(), 0);
				clearNameBtn.setVisibility(View.GONE);
				clearPasswordBtn.setVisibility(View.GONE);
				return false;
			}
		});

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				Bundle data = msg.getData();
				// Toast.makeText(SoujiayiLoginActivity.this,msg.obj.toString(),Toast.LENGTH_LONG).show();
				boolean isError = data.getBoolean(Constants.IS_ERROR, false);

				if (isError) {
					progressDialog.dismiss();
					Toast.makeText(
							SoujiayiLoginActivity.this,
							SoujiayiLoginActivity.this.getResources()
									.getString(R.string.login_failure),
							Toast.LENGTH_LONG).show();
				} else {
					int uid = (Integer) msg.obj;
					if (uid > 0) {
						SoujiayiLoginActivity.this.uid = uid;
						HashMap<String, String> parameters = new HashMap<String, String>();
						parameters.put("sid",
								((MyApplication) SoujiayiLoginActivity.this
										.getApplication()).getSessionId());
						parameters.put("uid", String.valueOf(uid));
						if (getMemberInfohttpRequester == null) {
							getMemberInfohttpRequester = new HttpRequester(SoujiayiLoginActivity.this,1,
									getMemberInfohandler);
						}

						getMemberInfohttpRequester.getMemberInfo(parameters);

						String type = "goods";
						parameters.put("type", type);
						getMemberInfohttpRequester.getFavorite(parameters);
					} else if (uid == -1) {
						progressDialog.dismiss();
						Toast.makeText(
								SoujiayiLoginActivity.this,
								SoujiayiLoginActivity.this.getResources()
										.getString(
												R.string.login_account_locked),
								Toast.LENGTH_LONG).show();
					} else if (uid == 0) {
						progressDialog.dismiss();
						Toast.makeText(
								SoujiayiLoginActivity.this,
								SoujiayiLoginActivity.this.getResources()
										.getString(R.string.login_failure),
								Toast.LENGTH_LONG).show();
					}
				}
			}
		};

		getMemberInfohandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				progressDialog.dismiss();

				// new
				// AlertDialog.Builder(SoujiayiLoginActivity.this).setMessage(msg.obj.toString()).create().show();
				Bundle data = msg.getData();

				if (msg.what == 'f') {
					List<Map<String, String>> list = (List<Map<String, String>>) msg.obj;
					if (list != null && list.size() > 0) {
						String type = "goods";
						databaseManager.deleteAllFavorites(type);
						databaseManager.insertFavorites(list, type);
					}
					count_to_uc++;
				} else {
					boolean isError = data
							.getBoolean(Constants.IS_ERROR, false);
					User user = new User();
					if (isError) {
						user.setType(Constants.USER_TYPE_SOUJIAYI);
						user.setUid(uid);
						user.setUsername(name.getText().toString());
						user.setPassword(password.getText().toString());
					} else if (msg.what == 'i') {
						user = (User) data.getSerializable(Constants.USER);
						user.setType(Constants.USER_TYPE_SOUJIAYI);
						user.setPassword(password.getText().toString());
						count_to_uc++;
					}
					databaseManager.insertUser(user);
					UserKeeper.keepUser(SoujiayiLoginActivity.this, user,
							Constants.PREFERENCES_NAME_USER);

				}

				if (count_to_uc >= 2) {
					if (isNotFromSetting) {
						SoujiayiLoginActivity.this.finish();
						Toast.makeText(
								SoujiayiLoginActivity.this,
								SoujiayiLoginActivity.this.getResources()
										.getString(R.string.login_success),
								Toast.LENGTH_LONG).show();
						overridePendingTransition(R.anim.push_down_in,
								R.anim.push_down_out);
					} else {
						Intent intent = new Intent(SoujiayiLoginActivity.this,
								UserCenterActivity.class);
						startActivity(intent);
						SoujiayiLoginActivity.this.finish();
						overridePendingTransition(R.anim.push_left_in,
								R.anim.push_left_out);
					}
				}
			}
		};

		httpRequester = new HttpRequester(this,1, handler);

	}

	public void back(View view) {
		if (isNotFromSetting) {
			this.finish();
			overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
		} else {
			Intent intent = new Intent(SoujiayiLoginActivity.this,
					SettingActivity.class);
			startActivity(intent);
			this.finish();
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
		}
	}

	public void clearName(View view) {
		name.setText("");
		clearNameBtn.setVisibility(View.GONE);
	}

	public void clearPassword(View view) {
		password.setText("");
		clearPasswordBtn.setVisibility(View.GONE);
	}

	public void login(View view) {
		String nameStr = name.getText().toString();
		String passwordStr = password.getText().toString();

		if (nameStr != null && !nameStr.equals("") && passwordStr != null
				&& !passwordStr.equals("")) {
			if (!NetworkUtils.isNetworkConnected(this)) {
				Toast.makeText(
						SoujiayiLoginActivity.this,
						SoujiayiLoginActivity.this
								.getString(R.string.network_unavailable_message),
						Toast.LENGTH_LONG).show();
				return;
			}

			progressDialog = new ProgressDialog(SoujiayiLoginActivity.this);
			progressDialog.setMessage(getResources().getString(
					R.string.login_loading));
			progressDialog.setCancelable(false);
			progressDialog.show();

			HashMap<String, String> parameters = new HashMap<String, String>();
			parameters.put("sid",
					((MyApplication) this.getApplication()).getSessionId());
			parameters.put("account", nameStr);
			parameters.put("passwd", passwordStr);
			count_to_uc = 0;
			httpRequester.login(parameters);
		}
	}

	public void register(View view) {
		Intent intent = new Intent(SoujiayiLoginActivity.this,
				RegisterActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	@Override
	protected void onDestroy() {
		databaseManager.closeDB();
		if (httpRequester != null) {
			httpRequester.close();
		}
		if (getMemberInfohttpRequester != null) {
			getMemberInfohttpRequester.close();
		}
		super.onDestroy();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (isNotFromSetting) {
				this.finish();
				overridePendingTransition(R.anim.push_down_in,
						R.anim.push_down_out);
			} else {
				Intent intent = new Intent(SoujiayiLoginActivity.this,
						SettingActivity.class);
				startActivity(intent);
				this.finish();
				overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
			return false;
		}
		return false;
	}

}
